package com.example.demo.utils;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;

public class FileUtil {
    // 直接使用hutool的IoUtil.copy()
    // 改进使用Buffered缓冲流
    public static void copyBytrandition(InputStream fis, OutputStream fos) {
        try {
            byte[] buf = new byte[1024 * 1024];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            colseStream(fis, fos);
        }
    }

    public static void mergeBio(List<File> files, OutputStream os) {
        InputStream is = null;
        try {
            for (File file : files) {
                is = new FileInputStream(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            colseStream(is, os);
        }

    }

    // 使用IoUtil.copyByNIO()
    public static void copyByNio(FileInputStream fis, FileOutputStream fos) {
        try {
            FileChannel sourceCh = fis.getChannel();
            FileChannel destCh = fos.getChannel();
            destCh.transferFrom(sourceCh, 0, sourceCh.size());
            sourceCh.close();
            destCh.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用IoUtil.copyByNIO()
    public static void copyByNio2(FileInputStream fis, FileOutputStream fos) {
        try {
            FileChannel sourceCh = fis.getChannel();
            FileChannel destCh = fos.getChannel();
            MappedByteBuffer mbb = sourceCh.map(FileChannel.MapMode.READ_ONLY, 0, sourceCh.size());
            destCh.write(mbb);
            sourceCh.close();
            destCh.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void colseStream(InputStream is, OutputStream os) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
